package 打牢基础30天.day02.my;

import 打牢基础30天.util.ArrUtil;

/**
 * @Author yaya
 * @Create 2024/6/13 10:41
 * Description:
 */
public class Code06_QuickSort_My {

    public static void quickSort(int[] arr){
        if (arr == null || arr.length < 2){
            return;
        }

        quickSort(arr, 0, arr.length - 1);
    }

    private static void quickSort(int[] arr, int left, int right) {
        if (left < right){
            // 随机数成为基准值，防止最坏情况--原本有序
            swap(arr, right, left + (int)(Math.random() * (right - left + 1)));
            int[] p = partition(arr,left, right);
            quickSort(arr,left,p[0] - 1);
            quickSort(arr,p[1] + 1,right);


        }
    }

    /**
     *
     * @param arr
     * @param left
     * @param right 基准值
     * @return
     */
    private static int[] partition(int[] arr, int left, int right) {
        int less = left - 1;
        int more = right;
        while (left < more){
            if (arr[left] < arr[right]){
                swap(arr, ++less, left++);
            }else if (arr[left] > arr[right]){
                swap(arr, --more,left);
            }else {
                left++;
            }
        }

        swap(arr, more, right);

        return new int[]{less + 1, more};
    }


    public static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    // for test
    public static void main(String[] args) {
        int testTime = 500000;
        int maxSize = 100;
        int maxValue = 100;
        boolean succeed = true;
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < testTime; i++) {
            int[] arr1 = ArrUtil.generateRandomArray(maxSize, maxValue);
            int[] arr2 = ArrUtil.copyArray(arr1);
            quickSort(arr1);
            ArrUtil.comparator(arr2);
            if (!ArrUtil.isEqual(arr1, arr2)) {
                succeed = false;
                break;
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("costTime:"+(endTime - startTime) + "ms");

        System.out.println(succeed ? "Nice!" : "Fucking fucked!");

        int[] arr = ArrUtil.generateRandomArray(maxSize, maxValue);
        ArrUtil.printArray(arr);
        quickSort(arr);
        ArrUtil.printArray(arr);
    }
}
